//
//  GYInvoiceViewController.m
//  GoodLuck
//
//  Created by apple on 2018/3/21.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//



#import "GYInvoiceViewController.h"
#import "GYNetWorkTools.h"
#import "GYInvoiceTableViewCell.h"
#import "GYAddInvoiceTableViewCell.h"
#import "GYInvoiceTypeTableViewCell.h"
#import "GYInvoiceTitleTableViewCell.h"
//#import "GYInvoiceContentTableViewCell.h"
//#import "GYInvoiceContentSelectedView.h"
@interface GYInvoiceViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIButton *noInvoiceBtu;
@property (weak, nonatomic) IBOutlet UIButton *invoiceInfoBtu;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

/** 表格数据源 */
@property (nonatomic, strong) NSMutableArray *invoiceList;
/** 代表当前总行数 */
@property (nonatomic, assign) NSInteger currentIndex;

//代表当前新增发票一行是否被选中
@property (nonatomic, getter=isSelected) BOOL selected;

/** 当前发票类型 */
@property (nonatomic, strong) NSString *invoiceType;

/** 当前发票的标题 */
@property (nonatomic, strong) NSString *invoiceTitle;

/** 当前发票内容 */
@property (nonatomic, strong) NSString *invoiceContent;

@property (nonatomic, getter=isTypeState) BOOL typeState;

/** 发票ID */
@property (nonatomic, strong) NSString  *invoice_id;

//代表是否需要发票选项
@property (nonatomic, getter=isInvoice) BOOL invoice;

/** 公司税号 */
@property (nonatomic, strong) NSString *invoiceTax;
@end

@implementation GYInvoiceViewController

- (IBAction)onClick:(UIButton *)sender {
    switch (sender.tag) {
        case 1:
        {
            self.invoice = NO;
            [self.invoiceList removeAllObjects];
            
            self.noInvoiceBtu.layer.borderWidth = 0;
            [self.noInvoiceBtu setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.noInvoiceBtu setBackgroundColor:RGBColor(15, 206, 194)];
            
            self.invoiceInfoBtu.layer.borderWidth = 2;
            [self.invoiceInfoBtu setTitleColor:RGBColor(125, 125, 125) forState:UIControlStateNormal];
            [self.invoiceInfoBtu setBackgroundColor:[UIColor whiteColor]];
        }
            break;
            
        case 2:
        {
            self.invoice = YES;
            self.noInvoiceBtu.layer.borderWidth = 2;
            [self.noInvoiceBtu setTitleColor:RGBColor(125, 125, 125) forState:UIControlStateNormal];
            [self.noInvoiceBtu setBackgroundColor:[UIColor whiteColor]];
            
            self.invoiceInfoBtu.layer.borderWidth = 0;
            [self.invoiceInfoBtu setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [self.invoiceInfoBtu setBackgroundColor:RGBColor(15, 206, 194)];

            //加载发票信息
            [self loadInvoiveInfo];
        }
            break;
            
        default:
            break;
    }
    
    //刷新表格展示发票的形式
    [self.tableview reloadData];
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
}

- (void)setupUI {
    
    self.currentIndex = 1;
    self.invoiceType = @"person";
    self.invoiceTitle = @"";
    self.typeState = YES;
    self.navigationItem.title = @"管理发票信息";
    
    //设置按钮的属性
    self.noInvoiceBtu.layer.cornerRadius = 4;
    self.noInvoiceBtu.layer.borderColor = RGBColor(221, 221, 221).CGColor;
    
    self.invoiceInfoBtu.layer.cornerRadius = 4;
    self.invoiceInfoBtu.layer.borderWidth = 2;
    self.invoiceInfoBtu.layer.borderColor = RGBColor(221, 221, 221).CGColor;
    
    //设置表格的尾视图
    UIView *headView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    headView.backgroundColor = [UIColor clearColor];
    self.tableview.tableHeaderView = headView;
    
    //设置tableView的尾视图
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    footView.backgroundColor = [UIColor clearColor];
    UIButton *btu = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, ScreenWidth-40, 44)];
    btu.titleLabel.font = [UIFont systemFontOfSize:18];
    [btu setTitle:@"确定" forState:UIControlStateNormal];
    [btu setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btu.layer.cornerRadius = 4;
    [btu setBackgroundColor:RGBColor(0, 158, 214)];//RGBColor(71, 163, 39)
    [btu addTarget:self action:@selector(confirmBtu:) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:btu];
    self.tableview.tableFooterView = footView;
}

- (void)loadInvoiveInfo {
    [EasyLodingView showLodingText:@"正在加载..."];
    [GYNetWorkTools requestInvoiceList:^(NSDictionary *obj) {
        //NSLog(@"object======%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            [EasyLodingView hidenLoding];
            NSArray *invoice_list = [datas objectForKey:@"invoice_list"];
            [self.invoiceList addObjectsFromArray:[GYInvoice jsonInvoiceInfo:invoice_list]];
            [self.tableview reloadData];
        }else if (code ==  400) {
            [EasyTextView showText:@"加载数据出错,请重新加载!"];
            [EasyLodingView hidenLoding];
        }
        
    } error:^(NSError *error) {
        [EasyTextView showText:@"加载数据出错,请重新加载!"];
        [EasyLodingView hidenLoding];
        NSLog(@"InvoiceListFailed====%@",error);
    }];
}



- (void)confirmBtu:(UIButton *)btu {
    if (self.isSelected) {
        //增加一个发票信息  并且放回
        if (![self.invoiceType isEqualToString:@"person"]) {
            if (self.invoiceTitle.length == 0 || self.invoiceTax.length == 0) {
                [EasyTextView showText:@"请填写完成信息!"];
                
                return;
            }
        }
        [GYNetWorkTools requestAddInvoice:self.invoiceType inv_title:self.invoiceTitle == nil ? @"" : self.invoiceTitle inv_content:self.invoiceContent == nil ? @"" :self.invoiceContent inv_code:self.invoiceTax == nil ? @"" : self.invoiceTax success:^(NSDictionary *obj) {
            //NSLog(@"invoice==========%@",obj);
            int code = [[obj objectForKey:@"code"] intValue];
            if (code == 200) {
                [EasyTextView showSuccessText:@"增加发票信息成功!"];
                NSDictionary *datas = [obj objectForKey:@"datas"];
                NSString *inv_id = [datas objectForKey:@"inv_id"];

                self.returnSelectInvoiceCallBack(self.invoiceTitle,inv_id);
                [self.navigationController popViewControllerAnimated:YES];
            }
        } error:^(NSError *error) {
            
        }];
    }else {
        self.returnSelectInvoiceCallBack(self.invoiceTitle,self.invoice_id);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.invoice) {
        return self.invoiceList.count+self.currentIndex;
    }else {
        return 0;
    }
    //return self.invoiceList.count == 0 ? 1 : self.invoiceList.count+self.currentIndex;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.row < self.invoiceList.count) {
        GYInvoiceTableViewCell *cell = [GYInvoiceTableViewCell cellWithTableView:tableView];
        cell.invoiceModel = self.invoiceList[indexPath.row];
        cell.refreshTableViewCallBack = ^(){
            //更新数据源, 刷新表格
            [weakSelf.invoiceList removeObjectAtIndex:indexPath.item];
            [tableView reloadData];
        };
        
        return cell;
        
        
    }else {
        switch (indexPath.row-self.invoiceList.count) {
            case 0:
            {
                GYAddInvoiceTableViewCell *cell = [GYAddInvoiceTableViewCell cellWithTableView:tableView];
                cell.addInvoice = self.isSelected;
                
                return cell;
            }
                break;
                
            case 1:
            {
                GYInvoiceTypeTableViewCell *cell = [GYInvoiceTypeTableViewCell cellWithTableView:tableView];
                cell.invoiceType = self.typeState;
                cell.selectInvoiceTypeCallBack = ^(NSInteger tag) {
                    
                    weakSelf.currentIndex = tag == 1 ? 2 : 4;
                    weakSelf.invoiceType = tag == 1 ? @"person" : @"company";
                    weakSelf.typeState = tag == 1 ? YES : NO;
                    
                    [tableView reloadData];
                };
                
                return cell;
            }
                break;
                
            case 2:
            {
//                if (self.currentIndex == 3) {
//                    GYInvoiceContentTableViewCell *cell = [GYInvoiceContentTableViewCell cellWithTableView:tableView];
//                    cell.invoiceContentLable.text = self.invoiceContent;
//
//                    return cell;
//                }else {
                    GYInvoiceTitleTableViewCell *cell = [GYInvoiceTitleTableViewCell cellWithTableView:tableView];
                    cell.invoiceTitleTF.placeholder = @"输入个人或企业名称";
                    cell.headTitle.text = @"公司抬头";
                    cell.invoiceTitleTF.text = self.invoiceTitle;
                    cell.invoiceTitleCallBack = ^(NSString *title){
                        weakSelf.invoiceTitle = title;
                    };
                    
                    return cell;
//                }
            }
                break;
                
            case 3:
            {
                GYInvoiceTitleTableViewCell *cell = [GYInvoiceTitleTableViewCell cellWithTableView:tableView];
                cell.invoiceTitleTF.placeholder = @"请输入公司税号";
                cell.headTitle.text = @"公司税号";
                cell.invoiceTitleTF.text = self.invoiceTax;
                cell.invoiceTitleCallBack = ^(NSString *title){
                    weakSelf.invoiceTax = title;
                };
                
                return cell;
            }
                break;
                
//            case 4:
//            {
//                GYInvoiceContentTableViewCell *cell = [GYInvoiceContentTableViewCell cellWithTableView:tableView];
//                cell.invoiceContentLable.text = self.invoiceContent;
//
//                return cell;
//            }
//                break;
                
            default:
                break;
        }
    }
    
    return  nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row < self.invoiceList.count) {
        GYInvoice *invoice = self.invoiceList[indexPath.row];
        //这里要判断 发票的类型是个人还是 公司
        self.invoiceTitle = invoice.inv_title;
        self.invoiceContent = invoice.inv_content;
        self.invoice_id = [NSString stringWithFormat:@"%d",invoice.inv_id];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.selected = NO;
            
            for (GYInvoice *model in self.invoiceList) {
                if (model.inv_id == invoice.inv_id) {
                    model.selectState = YES;
                }else {
                    model.selectState = NO;
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [tableView reloadData];
            });
        });
    }else if (indexPath.row == self.invoiceList.count){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.selected = YES;
            self.currentIndex = self.typeState ? 2 : 5;
            for (GYInvoice *model in self.invoiceList) {
                model.selectState = NO;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [tableView reloadData];
            });
        });
        
    }
//    else if (indexPath.row == self.invoiceList.count+self.currentIndex-1) {
//        //弹出一个发票理由选择器
//        GYInvoiceContentSelectedView *selectedView = [[GYInvoiceContentSelectedView alloc] initWithFrame:CGRectMake(0, self.view.height-240, ScreenWidth, 240)];
//        __weak typeof(self) weakSelf = self;
//        __weak UIView *weakView = selectedView;
//        selectedView.selectInvoiceContentCallBack = ^(NSString *content) {
//
//            weakSelf.invoiceContent = content;
//            [weakView removeFromSuperview];
//            [tableView reloadData];
//        };
//        [self.view addSubview:selectedView];
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}























#pragma mark -- 懒加载

- (NSMutableArray *)invoiceList {
    if (!_invoiceList) {
        _invoiceList = [NSMutableArray array];
    }
    
    return _invoiceList;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"selectInvoicetype" object:nil];
    
    NSLog(@"GYInvoiceViewController====dealloc");
}

@end
